﻿using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;

namespace StaticDemo.Identity
{
    /// <summary>
    /// 需要NuGet包
    /// Microsoft.Asp.Net.Identity.EntityFramework
    /// Microsoft.Asp.Net.Identity.Core
    /// Microsoft.AspNet.Identity.OWIN 
    /// Microsoft.Owin.Host.SystemWeb
    /// </summary>
    public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
    {

        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {

        }

        public new async Task<SignInStatus> ExternalSignInAsync(ExternalLoginInfo loginInfo, bool isPersistent)
        {
            SignInStatus lockedOut;
            ApplicationUser appUser = await UserManager.FindAsync(loginInfo.Login);
            if (appUser == null)
            {
                lockedOut = SignInStatus.Failure;
            }
            else
            {
                bool introduced15 = await UserManager.IsLockedOutAsync(appUser.Id);
                if (introduced15)
                {
                    lockedOut = SignInStatus.LockedOut;
                }
                else
                {
                    appUser.ExternalIdentity = loginInfo.ExternalIdentity;
                    await SignInAsync(appUser, isPersistent, false);
                    lockedOut = SignInStatus.Success;
                }
            }
            return lockedOut;
        }

        public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
        {
            return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
        }

        public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
        {
            return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
        }
    }
}